//
//  BlueToothManager.m
//  xy_hehu
//
//  Created by pac on 2019/4/28.
//  Copyright © 2019 pac. All rights reserved.
//

#import "BlueToothManager.h"
#import "XY_ShowSVP.h"
#import "ComonFile.h"

#define kPeripheralName @"XY-"    // 设备名字


#define kServiceUUID @"1000"             //服务的读UUID
#define kCharacteristicReadUUID @"1002"   //特性读
//00
#define kCharacteristicWriteUUID @"1001"//特性写

#define ISZYQTXT @"0" ///是否zyq测试

@interface BlueToothManager()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *centralManager;

@property (nonatomic, strong) CBPeripheral *selectedPeripheral;

@property (nonatomic,strong) CBCharacteristic * readCharacteristic;
@property (nonatomic,strong) CBCharacteristic * writeCharacteristic;
///定时器
@property (nonatomic,strong) NSTimer * timer;
///过期时间
@property (nonatomic,assign) NSInteger count;

@property (nonatomic,strong) NSTimer * timer2;



@end

@implementation BlueToothManager

+ (BlueToothManager *)shareBlueToothManager {
    static BlueToothManager * blueToothManager = nil;
    @synchronized(self) {
        if (blueToothManager == nil) {
            blueToothManager = [[BlueToothManager alloc]init];
            blueToothManager.isStart = NO;
            blueToothManager.isConnect = NO;

        }
    }
    return blueToothManager;
}


- (instancetype)init {
    self = [super init];
    if (self) {
//        [self blueToolInit];
    }
    return self;
}

- (void)blueToolInit {
    //         创建之后会马上检查蓝牙的状态,nil默认为主线程
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    self.count = 0;
    if (_timer == nil) {
        _timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

- (void)timerRun {
    _count ++;
    if (_count == 30) {
        NSLog(@"zzz关闭定时器");
        [self.timer setFireDate:[NSDate distantFuture]];
        [self.centralManager stopScan];
        [SVProgressHUD dismiss];
        _count = 0;
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"iphoneBTSearchWrong" object:nil];
//        if (_delegate && [_delegate respondsToSelector:@selector(blueToothStateChangeWithTag:)]) {
//            [_delegate blueToothStateChangeWithTag:4];
//            ///蓝牙搜索失败
//        }
        ///发送失败通知。
        [[NSNotificationCenter defaultCenter]postNotificationName:BlueToothStateChange object:@"4"];

        ///30 s 搜索失败
    }
}

#pragma mark - 蓝牙代理方法

// 蓝牙状态发生改变，这个方法一定要实现
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    _managerState = central.state;
    // 蓝牙状态可用
    if (central.state == CBCentralManagerStatePoweredOn) {
        // 如果蓝牙支持后台模式，一定要指定服务，否则在后台断开连接不上，如果不支持，可设为nil, option里的CBCentralManagerScanOptionAllowDuplicatesKey默认为NO, 如果设置为YES,允许搜索到重名，会很耗电
        [self.centralManager scanForPeripheralsWithServices:nil options:nil];
        [self.timer setFireDate:[NSDate distantPast]];
#warning 手机蓝牙已打开
    }else {
        _isConnect = NO;
        _isStart = NO;
        [XY_ShowSVP showSuccessSvpWithTitlte:NSLocalizedString(@"blue_checkBl", nil) WithDisplayTime:1.5];

//        [[NSNotificationCenter defaultCenter] postNotificationName:@"iphoneBTDisconnectPeripheral" object:nil];
//        if (_delegate && [_delegate respondsToSelector:@selector(blueToothStateChangeWithTag:)]) {
//            [_delegate blueToothStateChangeWithTag:2];
//            ///手机蓝牙断开（关闭了）
//        }
        [[NSNotificationCenter defaultCenter]postNotificationName:BlueToothStateChange object:@"2"];
    }
}


/**
 * 发现设备
 * @param peripheral 设备
 * @param advertisementData 广播内容
 * @param RSSI 信号强度
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    // 判断是否是你需要连接的设备
    if ([peripheral.name containsString:kPeripheralName] ||[peripheral.name containsString:@"RHCJB"]) {
        peripheral.delegate = self;
        self.selectedPeripheral = peripheral;
        NSLog(@"222%@",advertisementData);
        NSData * facturerData = advertisementData[@"kCBAdvDataManufacturerData"];
        NSString *address = facturerData.description;


        NSArray * firAry = [address componentsSeparatedByString:@","];
        if (firAry.count == 2) {
            NSString * bytes = firAry[1];
            NSArray * bytsArray = [bytes componentsSeparatedByString:@"0x"];
            if (bytsArray.count == 2) {
                NSString * finnalStr = bytsArray[1];
//                self.macAddress = [finnalStr removeLastStr];
//                if (self.macAddress.length > 1) {
//                    [[NSUserDefaults standardUserDefaults] setValue:self.macAddress forKey:MACAddress];
//                }

            }
        }

        // 开始连接设备
        [self.centralManager connectPeripheral:self.selectedPeripheral options:nil];
        _count = 0;
        [self.timer setFireDate:[NSDate distantFuture]];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"iphoneBTConnectPeripheral" object:nil];
//        if (_delegate && [_delegate respondsToSelector:@selector(blueToothStateChangeWithTag:)]) {
//            [_delegate blueToothStateChangeWithTag:0];
//            ///设备连接上蓝牙
//        }
        [[NSNotificationCenter defaultCenter]postNotificationName:BlueToothStateChange object:@"0"];
        
    }
    [SVProgressHUD showWithStatus:@"正在搜索设备"];

}


/**
 * 已经连接上设备
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    // 停止扫描
    [self.centralManager stopScan];
    // 发现服务
    [self.selectedPeripheral discoverServices:nil];
}


/**
 * 已经发现服务
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    for (CBService *service in peripheral.services) {
        if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
            // 根据你要的那个服务去发现特性
            [self.selectedPeripheral discoverCharacteristics:nil forService:service];
        }
        
    }
}
/**
 * 已经发现特性
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{

    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicWriteUUID]]) {
            NSLog(@"%@",characteristic);
            self.writeCharacteristic = characteristic;
            NSLog(@"写入功能赋值");
        }
        
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicReadUUID]]) {//暂时没用
            // 订阅特性，当数据频繁改变时，一般用它， 不用readValueForCharacteristic
            self.readCharacteristic = characteristic;
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            [peripheral readValueForCharacteristic:characteristic];
            NSLog(@"read功能赋值");
        }
    }
    _isConnect = YES;
//    [SVProgressHUD dismiss];
    [SVProgressHUD showSuccessWithStatus:@"连接成功"];

    [[NSNotificationCenter defaultCenter]postNotificationName:BlueToothStateChange object:@"1"];
    [self initTimer2];
    [self initTL];

}

/// 打开电极脱落指令
- (void)initTL {
    ///电极脱落90指令
    Project_ElectCheckSumModel * sunModle = [[Project_ElectCheckSumModel alloc]init];
    sunModle.head = @"AA";
    sunModle.lenth = @"02";
    sunModle.cmd = @"90";
    sunModle.data = @[@"01"];
    sunModle.end = @"55";
    [sunModle caculaterFinalStr];
    [self sendMessage:sunModle.finnalStr];///轮询
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {
    if (error != nil) {
        NSLog(@"zyq  updateWrong");
    }
    if (characteristic.isNotifying) {
        [peripheral readValueForCharacteristic:self.readCharacteristic];
    }else{
        NSLog(@"通知停止，所有外设断开");
        _isConnect = NO;
        
    }
}

/**
 * 数据更新的回调
 */
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    
    if (error == nil) {
        
    }else{
        return;
    }
    if ([characteristic.UUID.description isEqualToString:kCharacteristicReadUUID]) {
        // 这里收到的数据都是16进制，有两种转换，一种就直接转字符串，另一种是转byte数组，看用哪种方便
        
        // 直接转字符串
        NSString *orStr = characteristic.value.description;
        NSString *str = [orStr substringWithRange:NSMakeRange(1, orStr.length - 2)];
        NSString *dataStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
//        NSLog(@"xxxx%@",dataStr);
//        NSLog(@"%@",self);、
        //        0103000b00003408
//        if ([dataStr containsString:@"01"]&& dataStr.length > 4) {
            [self msgHandleWithStr:dataStr];
//        }
        
    }
    
}
/**
 * 设备连接断开
 */
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"zyq设备连接断开：%@", peripheral);
    _isStart = NO;//没有连接，视为没有开始工作。
    _isConnect = NO;
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"iphoneBTDisconnectPeripheral" object:nil];
//    [SVProgressHUD showSuccessWithStatus:@"设备断开连接"];
//    [SVProgressHUD dismissWithDelay:1.0];
//    if (_delegate && [_delegate respondsToSelector:@selector(blueToothStateChangeWithTag:)]) {
//        [_delegate blueToothStateChangeWithTag:3];
//        ///设备断开连接
//    }
    [[NSNotificationCenter defaultCenter]postNotificationName:BlueToothStateChange object:@"3"];

}

/**
 * 写入成功的回调， 如果类型是CBCharacteristicWriteWithoutResponse，不会走这个方法；
 */
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error == nil) {
        
    }else{
        NSLog(@"%@",error);
        return;
    }
    NSLog(@"zyq ---写入成功");
    [self.selectedPeripheral readValueForCharacteristic:self.readCharacteristic];

}

- (void)initTimer2 {
//    return;
    self.timer2 = [NSTimer scheduledTimerWithTimeInterval:2.f target:self selector:@selector(lookforCard) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer2 forMode:NSRunLoopCommonModes];
    
}

- (void)lookforCard {
    [self resetgetBlueStatr];
}

///一直轮询蓝牙，不然蓝牙会断开  rlgsx
- (void)resetgetBlueStatr {
    if (_isConnect == YES) {
        dispatch_queue_t queue = dispatch_queue_create(@"txtququ22", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            ///模式，脉宽，频率设置
            Project_ElectCheckSumModel * sunModle = [[Project_ElectCheckSumModel alloc]init];
            sunModle.head = @"AA";
            sunModle.lenth = @"02";
            sunModle.cmd = @"81";
            sunModle.data = @[@"00"];
            sunModle.end = @"55";
            [sunModle caculaterFinalStr];
            [self sendMessage:sunModle.finnalStr];///轮询
        });

    }
}


- (NSString *)extracted:(NSData *)cr16Data {
    return [cr16Data hexadecimalString];
}

- (NSArray *)getCrc16DataFromStr:(NSString *)str {
    NSData * hexData = [NSString convertHexStrToData:str];
    NSData * cr16Data = [hexData crc16];
    NSString * hexStr = [self extracted:cr16Data];
    NSArray * cr16Array = [NSString High_lowConversionWith:hexStr];
    return cr16Array;
}

#pragma mark -- 解析
///返回有效信息处理方法。
- (void)msgHandleWithStr:(NSString *)dataStr {
///在这里直接解析掉。 返回的是
    NSString * msgStr = dataStr;
    //    aa 0b 81 00 01 4d 0b4f00000000002955
    NSString * finnalStr = @"";
    if ([msgStr containsString:@","]) {
        NSArray * firAry = [msgStr componentsSeparatedByString:@","];
        if (firAry.count != 2) {
            return;
        }
        NSString * bytes = firAry[1];
        NSArray * bytsArray = [bytes componentsSeparatedByString:@"0x"];
        if (bytsArray.count != 2) {
            return;
        }
        finnalStr =   bytsArray[1];
    }else{
        finnalStr = msgStr;
    }
    if (finnalStr.length < 10) {
        return;
    }
    
    [[NSNotificationCenter defaultCenter]postNotificationName:BlueToothMsgReturnWithStr object:finnalStr];
//    NSLog(@"返回信息111%@",dataStr);



}

- (void)sendMsgBy16Data:(NSString *)TimeCRC {
    NSArray * array = [self getCrc16DataFromStr:TimeCRC];
    if (array.count == 2) {
        NSString * finalTimeStr = [NSString stringWithFormat:@"%@%@%@",TimeCRC,array[0],array[1]];
        [self sendMessage:finalTimeStr];
    }else{
        [XY_ShowSVP showSuccessSvpWithTitlte:@"***TimeRcrc错误..***" WithDisplayTime:1.5];

    }
}
///关闭外设蓝牙
- (void)getBlueToothOff {
    NSString * TimeCRC = BlueToothOff;//发送指令
    NSArray * array = [self getCrc16DataFromStr:TimeCRC];
    if (array.count == 2) {
        NSString * finalTimeStr = [NSString stringWithFormat:@"%@%@%@",TimeCRC,array[0],array[1]];
        [self sendMessage:finalTimeStr];
    }else{
        [XY_ShowSVP showSuccessSvpWithTitlte:@"GetStateRcrc错误.." WithDisplayTime:1.5];

    }
}

///获取蓝牙设备状态
- (void)getBlueToothState {
    NSString * TimeCRC = BlueToothGetState;//发送指令
    NSArray * array = [self getCrc16DataFromStr:TimeCRC];
    if (array.count == 2) {
        NSString * finalTimeStr = [NSString stringWithFormat:@"%@%@%@",TimeCRC,array[0],array[1]];
        [self sendMessage:finalTimeStr];
    }else{
        [XY_ShowSVP showSuccessSvpWithTitlte:@"GetStateRcrc错误.." WithDisplayTime:1.5];

    }
}

- (void)getBlueToothDefautSetting {
    [self sendMsgBy16Data:BlueToothGetTime];
    [self sendMsgBy16Data:BlueToothGetChufang];
    [self sendMsgBy16Data:BlueToothGetPower];
}

#pragma mark -- 发送信息func
- (void)sendMessage:(NSString *)msg {
    if (self.writeCharacteristic) {
        NSData *sendData =[NSString convertHexStrToData:msg];
        [self.selectedPeripheral writeValue:sendData forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    }
    
}



- (void)sendChufang:(NSString *)str {
    NSString * TimeCRC = BlueToothSetChufang([str hexadecimaTtoDecimal]);//发送指令
    NSArray * array = [self getCrc16DataFromStr:TimeCRC];
    if (array.count == 2) {
        NSString * finalTimeStr = [NSString stringWithFormat:@"%@%@%@",TimeCRC,array[0],array[1]];
        [self sendMessage:finalTimeStr];
    }else{
        [XY_ShowSVP showSuccessSvpWithTitlte:@"poweRcrc错误.." WithDisplayTime:1.5];

    }
}


#pragma mark - 主动断开和重连连接设备

/**
 * 断开连接
 */
- (IBAction)cancelConnect:(id)sender {
    if (self.selectedPeripheral) {
        [self.centralManager cancelPeripheralConnection:self.selectedPeripheral];
    }
}

/**
 * 重新连接
 */

- (void)reConnect {
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:nil];
}





@end
